package middle;

import util.PrintUtils;

public class Solution_289 {

    public static void main(String[] args) {
        Solution_289 model = new Solution_289();
//        int[][] ints = {{0,1,0},{0,0,1},{1,1,1},{0,0,0}};
        int[][] ints = {{1, 1},{1, 0}};
        model.gameOfLife(ints);
        for (int[] anInt : ints) {
            PrintUtils.arrayInt(anInt);
        }
//        PrintUtils.transfer("[[0,1,0],[0,0,1],[1,1,1],[0,0,0]]");
    }

    private int row, col;
    private final int[] row_direct = new int[]{-1, 0, 1};
    private final int[] col_direct = new int[]{-1, 0, 1};

    public void gameOfLife(int[][] board) {
        row = board.length;
        col = board[0].length;
        int[][] arrays = new int[row][col];
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                isChange(board, i, j, arrays);
            }
        }
        for (int i = 0; i < arrays.length; i++) {
            for (int j = 0; j < arrays[i].length; j++) {
                board[i][j] = arrays[i][j];
            }
        }
    }

    private void isChange(int[][] board, int i, int j, int[][] arrays) {
        if (cross(i, j)) {
            return;
        }
        int count = 0;
        for (int row_offset : row_direct) {
            for (int col_offset : col_direct) {
                int ii = i + row_offset;
                int jj = j + col_offset;
                if ((ii == i && jj == j) || cross(ii, jj) || board[ii][jj] == 0) {
                    continue;
                }
                count++;
            }
        }
        if (board[i][j] == 1) {
            if (count < 2) {
                arrays[i][j] = 0;
                return;
            } else if (count > 3) {
                arrays[i][j] = 0;
                return;
            }
        } else if (count == 3){
            arrays[i][j] = 1;
            return;
        }
        arrays[i][j] = board[i][j];
        return;
    }

    private boolean cross(int i, int j) {
        return i < 0 || i >= row || j < 0 || j >= col;
    }

    static class Positive {
        public int x;
        public int y;

        public Positive(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
}
